package com.zsrt.bbu.card.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsrt.bbu.card.entity.CardEntity;
import com.zsrt.bbu.card.service.CardService;
import com.zsrt.bbu.card.service.impl.CardServiceImpl;
import com.zsrt.utils.GsonUtil;

public class CardController  extends HttpServlet{
	
	private static final long serialVersionUID = 7360423272684888874L;
	
	
	private CardService service  = new CardServiceImpl();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method = request.getParameter("method");
		//1调用service层的方法  要准备1个袋子map用来拿service层返回的结果..
		Map<String, Object> map  = new HashMap<String, Object>();
		
		//2调用各种业务方法 crud
		if("add".equals(method)){
			CardEntity entity = new CardEntity();
			entity.setCardNo(request.getParameter("cardNo"));
			entity.setChip(request.getParameter("chip"));
			
			String bal =request.getParameter("balance");
			if(bal != null && !"".equals(bal)){
				entity.setBalance(Double.parseDouble(bal));
			}
			
			String bd= request.getParameter("bankId");
			if(null != bd && !"".equals(bd)){
				entity.setBankId(Integer.parseInt(bd));
			}
			
			entity.setOwner(request.getParameter("owner"));
			
			
			service.add(entity, map);
		}else if ("findAllCards".equals(method)){
			
			service.findAllCards(map);
			
			
		}else if ("findById".equals(method)){
			
			
			String id  = request.getParameter("id");
			
			if(null !=id && !"".equals(id)){
				service.findById(Integer.parseInt(id),map);
			}
			
			
		}else if ("update".equals(method)){
			
			CardEntity entity = new CardEntity();
			
			//修改的逻辑仅仅比新增的逻辑加多了一个字段   id  
			String id = request.getParameter("id");
			
			if(id !=null && !"".equals(id)){
				entity.setId(Integer.parseInt(id));
				
			}
			entity.setCardNo(request.getParameter("cardNo"));
			entity.setChip(request.getParameter("chip"));
			
			//凡是需要强转  强转成int double date...
			String bal =request.getParameter("balance");
			if(bal != null && !"".equals(bal)){
				entity.setBalance(Double.parseDouble(bal));
			}
			
			String bd= request.getParameter("bankId");
			if(null != bd && !"".equals(bd)){
				entity.setBankId(Integer.parseInt(bd));
			}
			
			entity.setOwner(request.getParameter("owner"));
			
			service.update(entity, map);
			
			
		}
		
		//3 把最终的结果以json格式返回给前台页面
		GsonUtil.printJson(response, map);
		
		
	}

}
